package com.cloudptt.api.product.pjsua2;

import android.view.SurfaceHolder;

import com.cloudptt.api.product.log.Log;

import org.pjsip.pjsua2.VideoWindow;
import org.pjsip.pjsua2.VideoWindowHandle;

public class VideoSurfaceHandler implements SurfaceHolder.Callback {
    private SurfaceHolder holder;
    private VideoWindow videoWindow = null;
    private boolean active = false;

    public VideoSurfaceHandler(SurfaceHolder holder_) {
        holder = holder_;
    }

    public void setVideoWindow(VideoWindow vw) {
        videoWindow = vw;
        active = true;
        setSurfaceHolder(holder);
    }

    public void resetVideoWindow() {
        active = false;
        videoWindow = null;
    }

    private void setSurfaceHolder(SurfaceHolder holder) {
        Log.debug(this.getClass(),"setSurfaceHolder active = " + active);
        if (!active) return;

        try {
            if(videoWindow != null) {
                VideoWindowHandle wh = new VideoWindowHandle();
                if(holder == null)
                {
                    Log.debug(this.getClass(),"setSurfaceHolder holder == null");
                }
                wh.getHandle().setWindow(holder != null ? holder.getSurface() : null);
                videoWindow.setWindow(wh);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h)
    {
        setSurfaceHolder(holder);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) { }


    @Override
    public void surfaceDestroyed(SurfaceHolder holder)
    {
        setSurfaceHolder(null);
//        boolean surfaceStillValid = false;
//        try {
//            surfaceStillValid = holder.lockCanvas(null) != null;
//        } catch (Exception e) {
//            // 忽略异常，可能 Surface 已经被销毁
//        }
//        if (!surfaceStillValid) {
//            // Surface 已经不在了，无需解锁
//        }
//        else {
//            holder.unlockCanvasAndPost(canvas); // 解锁 Canvas
//        }
    }
}
